pub mod custom;
pub mod generators;

use std::collections::HashMap;
use serde_json::Value;
use crate::error::{DataForgeError, Result};

// 核心生成器 Trait
pub trait Generator: Send + Sync {
    fn generate(&self) -> Value;
}

// 类型别名简化复杂类型
type CustomGenerator = Box<dyn Fn() -> Value + Send + Sync>;

// 数据生成器注册表
#[derive(Default)]
pub struct DataForge {
    generators: HashMap<&'static str, CustomGenerator>,
    lang: Language,
}

#[derive(Debug, Clone, Copy, Default)]
pub enum Language {
    #[default]
    ZhCN,
    EnUS,
    JaJP,
}

impl DataForge {
    /// 创建新的数据生成器实例
    pub fn new(lang: Language) -> Self {
        let mut df = Self {
            generators: HashMap::new(),
            lang,
        };
        df.register_builtin_generators();
        df
    }

    /// 注册内置生成器
    fn register_builtin_generators(&mut self) {
        self.generators.insert("uuid_v4", Box::new(|| crate::generators::uuid_v4()));
        self.generators.insert("zh_cn_name", Box::new(|| crate::generators::name::zh_cn_fullname()));
        self.generators.insert("en_name", Box::new(|| crate::generators::name::en_fullname()));
        self.generators.insert("email", Box::new(|| crate::generators::internet::email()));
        self.generators.insert("datetime_now", Box::new(|| crate::generators::datetime::now()));
        self.generators.insert("province", Box::new(|| crate::regions::china::province()));
    }

    /// 生成数据
    pub fn generate(&self, generator_name: &str) -> Option<Value> {
        self.generators.get(generator_name).map(|gen| gen())
    }

    /// 注册自定义生成器
    pub fn register<F>(&mut self, name: &'static str, generator: F)
    where
        F: Fn() -> Value + Send + Sync + 'static,
    {
        self.generators.insert(name, Box::new(generator));
    }

    /// 获取当前语言设置
    pub fn language(&self) -> Language {
        self.lang
    }

    /// 设置语言
    pub fn set_language(&mut self, lang: Language) {
        self.lang = lang;
    }

    /// 批量生成数据
    pub fn generate_batch(&self, generator_name: &str, count: usize) -> Result<Vec<Value>> {
        let generator = self.generators.get(generator_name)
            .ok_or_else(|| DataForgeError::generator(format!("Generator '{}' not found", generator_name)))?;
        
        Ok((0..count).map(|_| generator()).collect())
    }
}

impl Language {
    /// 获取语言代码
    pub fn code(&self) -> &'static str {
        match self {
            Language::ZhCN => "zh-CN",
            Language::EnUS => "en-US", 
            Language::JaJP => "ja-JP",
        }
    }
}